package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.em.sensitivewordsmonitor.ReceiverTypeEnum;
import com.pactera.madp.cp.api.em.sensitivewordsmonitor.SourceEnum;
import com.pactera.madp.cp.api.em.workmessage.MsgTypeEnum;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkRoomEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveMatchingRuleEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordsMonitorEntity;
import com.pactera.madp.cp.api.entity.wm.WorkMsgConfigEntity;
import com.pactera.madp.cp.api.entity.wm.WorkMsgEntity;
import com.pactera.madp.cp.mapper.wm.WorkMsgConfigMapper;
import com.pactera.madp.cp.mapper.wm.WorkMsgMapper;
import com.pactera.madp.cp.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:会话内容配置实现类
 * @author: Huayu
 * @time: 2020/11/25 11:43
 */
@Service
public class WorkMsgConfigServiceImpl extends ServiceImpl<WorkMsgConfigMapper, WorkMsgConfigEntity> implements IWorkMsgConfigService {

    @Resource
    private WorkMsgMapper workMsgMapper;
    @Autowired
    private ISensitiveWordService sensitiveWordServiceImpl;
    @Autowired
    private IWorkEmployeeService workEmployeeServiceImpl;
    @Autowired
    private IWorkContactService workContactServiceImpl;
    @Autowired
    private IWorkRoomService workRoomServiceImpl;
    @Autowired
    private IWorkMsgService workMsgServiceImpl;
    @Autowired
    private ISensitiveWordsMonitorService sensitiveWordsMonitorServiceImpl;
    @Autowired
    private SensitiveMatchingRuleService sensitiveMatchingRuleService;

    @Override
    public WorkMsgConfigEntity getByCorpId(Integer corpId) {
        List<WorkMsgConfigEntity> list = lambdaQuery().eq(WorkMsgConfigEntity::getCorpId, corpId)
                .orderByDesc(WorkMsgConfigEntity::getId)
                .list();
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public List<WorkMsgConfigEntity> getAllAble() {
        return baseMapper.selectAll();
    }

    @Override
    public boolean createWorkMessageConfig(WorkMsgConfigEntity workMsgConfigEntity) {
        return this.save(workMsgConfigEntity);
    }

    @Override
    public void getWorkMsgByCorpId(String corpIds, String s) {
        String[] corpIdArr = corpIds.split(",");
        Map<Integer, List<WorkMsgEntity>> map = null;
        for (String string:
                corpIdArr) {
            int corpId = Integer.valueOf(string) % 10;
            List<SensitiveWordsMonitorEntity> list = sensitiveWordsMonitorServiceImpl.list(Wrappers.<SensitiveWordsMonitorEntity>lambdaQuery()
                    .eq(SensitiveWordsMonitorEntity::getCorp_id,string)
                    .orderByDesc(SensitiveWordsMonitorEntity::getTriggerTime));
            List<WorkMsgEntity> workMsgConfigEntityList = new LinkedList<>();
            if (!list.isEmpty()){
                workMsgConfigEntityList=workMsgMapper.selectMsgByCorpIdByTriggerTime(String.valueOf(corpId),list.get(0).getTriggerTime().getTime()+1000);
            }else {
                workMsgConfigEntityList= workMsgMapper.selectMsgByCorpId(String.valueOf(corpId));
            }
            if (!workMsgConfigEntityList.isEmpty()){
                //根据corpId分组
                map = workMsgConfigEntityList.stream().collect(Collectors.groupingBy(WorkMsgEntity::getCorpId));
            }
        }
        //查询企业全部敏感词
        List<SensitiveWordEntity> sensitiveWordEntityList = sensitiveWordServiceImpl.getSensitiveWordsByCorpIdStatus(corpIdArr,1,"id,corp_id,name,employee_num,contact_num");
        //对敏感词按企业分类
        Map<Integer,List<SensitiveWordEntity>> corpMap = sensitiveWordEntityList.stream().collect(Collectors.groupingBy(SensitiveWordEntity::getCorpId));
        //敏感词触发次数统计
        Integer updateWords = 0;
        //敏感词触发记录
        Integer createMonitors = 0;
        //查询消息数据列表-根据企业ID
        Map map2 = null;
        List<Map> map2List = new ArrayList();
        if (map != null){
            for (Map.Entry<Integer, List<WorkMsgEntity>> map1: map.entrySet()) {
                Integer key = map1.getKey();
                List<SensitiveWordEntity> sensitiveWordEntityList1 = new LinkedList<>();
                if(corpMap.get(key) != null){
                    List<SensitiveWordEntity> entities = corpMap.get(key);
                    entities.forEach(e->{
                        sensitiveWordEntityList1.add(e);
                    });

                }else{
                    continue;
                }
                List<WorkMsgEntity> workMsgEntityList = workMsgServiceImpl.getWorkMessagesByMsgId(map1.getValue());
                if(workMsgEntityList.isEmpty()){
                    continue;
                }

                LinkedList<SensitiveMatchingRuleEntity> entities = new LinkedList<>();
                sensitiveWordEntityList1.forEach(ss->{
                    List<SensitiveMatchingRuleEntity> list = sensitiveMatchingRuleService.list(Wrappers.<SensitiveMatchingRuleEntity>lambdaQuery().eq(SensitiveMatchingRuleEntity::getSensitiveId, ss.getId()));
                    entities.addAll(list);
                });
                map2 = new HashMap<>();
                map2 = matchWords(workMsgEntityList,entities,key);
                map2List.add(map2);
            }
            //将数据入表
            insertData(map2List);
        }
    }


    /**
     *
     *
     * @description:敏感词统计数据
     * @return:
     * @author: Huayu
     * @time: 2021/3/11 8:41
     */
    private void insertData(List<Map> map2List) {
        for (Map map: map2List) {
            if (map.get("updateWords") != null) {
                List<SensitiveWordEntity> updateWords = JSONArray.parseArray(JSONUtil.toJsonStr(map.get("updateWords")), SensitiveWordEntity.class);
                updateWords.forEach(u -> {
                    sensitiveWordServiceImpl.updateSensitiveWordById(u.getId(), u.getEmployeeNum(), u.getContactNum());
                });
            }
            if (map.get("createMonitors") != null) {
                //创建触发敏感词记录
                sensitiveWordsMonitorServiceImpl.createSensitiveWordMonitors(map);
                updateContactNumAndEmployeeNum();
            }
        }
    }

    /**
     * 修改敏感词触发次数
     */
    private void updateContactNumAndEmployeeNum(){
        QueryWrapper<SensitiveWordsMonitorEntity> wrapper = new QueryWrapper<>();
        wrapper.select("sensitive_word_id,count(sensitive_word_id) as count ,source");
        wrapper.groupBy("sensitive_word_id,source");
        List<Map<String, Object>> maps = sensitiveWordsMonitorServiceImpl.listMaps(wrapper);
        maps.forEach(l->{
            SensitiveWordEntity wordEntity = new SensitiveWordEntity();
            wordEntity.setId(Integer.valueOf(l.get("sensitive_word_id").toString()));
            Integer source = Integer.valueOf(l.get("source").toString());
            if (source == 1){
                wordEntity.setContactNum(Integer.valueOf(l.get("count").toString()));
            }else {
                wordEntity.setEmployeeNum(Integer.valueOf(l.get("count").toString()));
            }

            sensitiveWordServiceImpl.updateById(wordEntity);
        });
    }



    /**
     *
     *
     * @description: 企业设置敏感词列表
     * @return:
     * @author: Huayu
     * @time: 2021/3/9 18:15
     */
    private Map matchWords(List<WorkMsgEntity> workMsgEntityList, List<SensitiveMatchingRuleEntity> sensitiveWordEntityList1, Integer corpId) {
        //敏感词触发次数统计
        LinkedList<SensitiveWordEntity> wordEntities = new LinkedList<>();
        //敏感词触发记录
        Map<String,Object> matchWordsMap = new HashMap();
        //获得信息发送方|接收方信息
        List<String> froms = new ArrayList();
        List<String> tolists = new ArrayList();
        List<String> wxRoomIdArr = new ArrayList();
        for (WorkMsgEntity workMsgEntity: workMsgEntityList) {

            froms.add(workMsgEntity.getFrom());
            List<String> stringList = JSONArray.parseArray(workMsgEntity.getTolist(), String.class);
            tolists.addAll(stringList);
            if(!workMsgEntity.getWxRoomId().equals("")){
                wxRoomIdArr.add(workMsgEntity.getWxRoomId());
            }
        }

        Map userListMap = null;
        Map contactListMap = null;
        Map roomListMap = null;
        if (!froms.isEmpty() && !tolists.isEmpty()){
            userListMap = getEmployeeList(corpId,froms,tolists);
            contactListMap = getContactList(corpId,froms,tolists);
        }

        //触发场景群聊
        if (!wxRoomIdArr.isEmpty()){
             roomListMap = getRoomList(wxRoomIdArr);
        }
        List<SensitiveWordsMonitorEntity> entities = new LinkedList<>();
        for (WorkMsgEntity message:workMsgEntityList) {
            //过滤非文本信息
            if(!message.getMsgType().equals(MsgTypeEnum.TEXT.getCode())){
                continue;
            }

            //过滤-非本公司员工|客户触发的信息
            if(userListMap != null && contactListMap != null && (userListMap.get(message.getFrom()) == null) && (contactListMap.get(message.getFrom()) == null)){
                continue;
            }

            //过滤内部群信息
            if( roomListMap != null && !message.getWxRoomId().isEmpty() && (roomListMap.get(message.getWxRoomId()) == null)){
                continue;
            }

            if(message.getContent() == null || message.getContent().isEmpty()){
                continue;
            }
            //触发来源
            WorkEmployeeEntity triggerInfo = null;
            WorkContactEntity triggerInfo1 = null;
            if(userListMap.get(message.getFrom()) != null){
                triggerInfo = (WorkEmployeeEntity)userListMap.get(message.getFrom());
            }else{
                if (contactListMap != null){
                    triggerInfo1 = (WorkContactEntity)contactListMap.get(message.getFrom());
                }
            }
            //接收者类型
            Integer receiverType = null;
            Integer receiverId = null;
            String receiverName = null;
            if(!message.getWxRoomId().isEmpty() && roomListMap != null){
                receiverType = ReceiverTypeEnum.ROOM.getCode();
                receiverId = ((WorkRoomEntity)roomListMap.get(message.getWxRoomId())).getId();
                receiverName = ((WorkRoomEntity)roomListMap.get(message.getWxRoomId())).getName();
            }else if(userListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0)) != null){
                receiverType = ReceiverTypeEnum.EMPLOYEE.getCode();
                receiverId = ((WorkEmployeeEntity)userListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0))).getId();
                receiverName = ((WorkEmployeeEntity)userListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0))).getName();
            }else {
                if (contactListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0)) != null){
                    receiverType = ReceiverTypeEnum.CONTACT.getCode();
                    receiverId = ((WorkContactEntity)contactListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0))).getId();
                    receiverName = ((WorkContactEntity)contactListMap.get(JSONArray.parseArray(message.getTolist(),String.class).get(0))).getName();
                }
            }
            SensitiveWordsMonitorEntity entity = new SensitiveWordsMonitorEntity();
            entity.setCorp_id(corpId);
            entity.setSource((userListMap.get(message.getFrom()) != null) ? SourceEnum.EMPLOYEE.getCode() :SourceEnum.CONTACT.getCode());
            Integer id = null;
            String name = null;
            if(triggerInfo != null){
                id = triggerInfo.getId();
                name = triggerInfo.getName();
            }else{
                id = triggerInfo1.getId();
                name = triggerInfo1.getName();
            }

            entity.setTriggerId(id);
            entity.setTriggerName(name);
            entity.setReceiverId(receiverId);
            entity.setReceiverType(receiverType);
            entity.setReceiverName(receiverName);
            entity.setTriggerTime(new Date(Long.parseLong(String.valueOf(message.getMsgTime()))));
            entity.setWorkMessageId(message.getSeq());
            List<Map> map = getChatContent(String.valueOf(corpId), message);
            entity.setChatContent(map.isEmpty() ? null : JSONUtil.toJsonStr(map));
            entity.setCreateTime(LocalDateTime.now());

            for (SensitiveMatchingRuleEntity sensitiveMatchingRuleEntity: sensitiveWordEntityList1) {
//                SensitiveWordEntity wordEntity = new SensitiveWordEntity();
                //监测-是否触发敏感词
                if(!message.getContent().toUpperCase().contains(sensitiveMatchingRuleEntity.getMatchingRule().toUpperCase())){
                    continue;
                }
                SensitiveWordEntity sensitiveWordEntity = sensitiveWordServiceImpl
                        .getOne(Wrappers.<SensitiveWordEntity>lambdaQuery().eq(SensitiveWordEntity::getId, sensitiveMatchingRuleEntity.getSensitiveId()));

//                wordEntity.setId(sensitiveWordEntity.getId());
//                wordEntity.setEmployeeNum(sensitiveWordEntity.getEmployeeNum());
//                wordEntity.setContactNum(sensitiveWordEntity.getContactNum());
//                //触发来源
//                if(userListMap.get(message.getFrom()) != null){
//                   wordEntity.setEmployeeNum(wordEntity.getEmployeeNum()+1);
//                }else{
//                   wordEntity.setContactNum(wordEntity.getContactNum()+1);
//                }

                entity.setSensitiveWordId(sensitiveWordEntity.getId());
                entity.setSensitiveWordName(sensitiveWordEntity.getName());
                entities.add(entity);
//                wordEntities.add(wordEntity);
            }

        }
        entities=entities.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(SensitiveWordsMonitorEntity::getWorkMessageId).thenComparing(SensitiveWordsMonitorEntity::getSensitiveWordId))),ArrayList::new));
//        matchWordsMap.put("updateWords",wordEntities);
        matchWordsMap.put("createMonitors",entities);
        return matchWordsMap;
    }


    /**
     *
     *
     * @description:单条会话信息
     * @return:
     * @author: Huayu
     * @time: 2021/3/10 14:46
     */
    private List<Map> getChatContent(String corpId, WorkMsgEntity message) {
        List<WorkMsgEntity> beforeList = null;
        List<WorkMsgEntity> afterList = null;
        DateTime dateTime = DateUtil.date(Long.parseLong(message.getMsgTime()));
        long startTime = DateUtil.beginOfDay(dateTime).getTime();
        long endTime = DateUtil.endOfDay(dateTime).getTime();
        if(!message.getWxRoomId().isEmpty()){
            beforeList = new ArrayList();
            afterList = new ArrayList();
            //查询此条信息前十条
            beforeList = workMsgServiceImpl.getWorkMessagesRangeByCorpIdWxRoomId(corpId,message.getWxRoomId(),message.getSeq(),0,startTime,endTime);
            //查询此条信息后十条
            afterList = workMsgServiceImpl.getWorkMessagesRangeByCorpIdWxRoomId(corpId,message.getWxRoomId(),message.getSeq(),1,startTime,endTime);
        }else{
            beforeList = new ArrayList();
            afterList = new ArrayList();
            //查询此条信息前十条
            beforeList = workMsgServiceImpl.getWorkMessagesRangeByCorpId(corpId,message.getFrom(),message.getTolist(),message.getSeq(),0, startTime, endTime);
            //查询此条信息后十条
            afterList = workMsgServiceImpl.getWorkMessagesRangeByCorpId(corpId,message.getFrom(),message.getTolist(),message.getSeq(),1, startTime, endTime);
        }
        beforeList.addAll(afterList);
        beforeList = beforeList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WorkMsgEntity::getMsgTime))), ArrayList::new));
        List<String> fromIdArr = new ArrayList();
        for (WorkMsgEntity workMsgEntity: beforeList) {
            fromIdArr.add(workMsgEntity.getFrom());
        }
        List<Map> list = new LinkedList<>();
        if (!fromIdArr.isEmpty()){
            Map fromUserList = getEmployeeList(Integer.valueOf(corpId), fromIdArr,fromIdArr);
            Map fromContactList = getContactList(Integer.valueOf(corpId), fromIdArr,fromIdArr);

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (WorkMsgEntity workMsgEntity:
                    beforeList) {
                Map map =  new HashMap();
                map.put("isTrigger",workMsgEntity.getSeq().equals(message.getSeq()) ? 1 : 0);
                map.put("sender",handleMessageSender(workMsgEntity,fromUserList,fromContactList));
                map.put("sendTime",formatter.format(new Date(Long.parseLong(String.valueOf(workMsgEntity.getMsgTime())))));
                map.put("msgType",workMsgEntity.getMsgType());
                map.put("msgContent",workMsgEntity.getContent());
                list.add(map);
            }
        }
        return list;

    }


    /**
     *
     *
     * @description:会话消息 触发员工信息 触发客户信息
     * @return:
     * @author: Huayu
     * @time: 2021/3/10 18:13
     */
    private String handleMessageSender(WorkMsgEntity workMsgEntity, Map fromUserList, Map fromContactList) {
        String sender = "系统";
        //发送人微信唯一标识前缀
        String prefixFrom = workMsgEntity.getFrom().substring(0, workMsgEntity.getFrom().length() - (workMsgEntity.getFrom().length()-2));
        //机器人
        if(prefixFrom.equals("we")){
            sender = "机器人";
            //客户
        }else if(prefixFrom.equals("wo") || prefixFrom.equals("wm")){
            sender =  fromContactList.get(workMsgEntity.getFrom()) != null ? (( WorkContactEntity)fromContactList.get(workMsgEntity.getFrom())).getName():workMsgEntity.getFrom();
            //员工
        }else{
            sender = fromUserList.get(workMsgEntity.getFrom()) != null ? ((WorkEmployeeEntity)fromUserList.get(workMsgEntity.getFrom())).getName():workMsgEntity.getFrom();
        }
        return sender;
    }


    /**
     *
     *
     * @description:微信群聊ID
     * @return:
     * @author: Huayu
     * @time: 2021/3/10 9:36
     */
    private Map getRoomList(List<String> wxRoomIdArr) {
        List<WorkRoomEntity> workRoomEntityList = workRoomServiceImpl.getWorkRoomsByChatId(wxRoomIdArr,"id, wx_chat_id, name");
        Map<String,Object> map = null;
        for (WorkRoomEntity workRoomEntity:
                workRoomEntityList) {
            map = new HashMap();
            map.put(workRoomEntity.getWxChatId(),workRoomEntity);
        }
        return map;
    }


    /**
     *
     *
     * @description:根据微信外部联系人ID获取外部联系人
     * @return:
     * @author: Huayu
     * @time: 2021/3/9 18:36
     */
    private Map<String, Object> getContactList(Integer corpId, List<String> froms,List<String> tolists) {
        List<WorkContactEntity> workContactEntityList = workContactServiceImpl.getWorkContactByCorpIdWxExternalUserIds(corpId,froms,tolists,"id,wx_external_userid,name");
        Map<String,Object> map = new HashMap<>();
        //组装map并返回
        for (WorkContactEntity workContactEntity: workContactEntityList) {
            map.put(workContactEntity.getWxExternalUserid(),workContactEntity);
        }
        return map;
    }


    /**
     *
     *
     * @description:根据微信用户Id获取员工
     * @return:
     * @author: Huayu
     * @time: 2021/3/9 18:36
     */
    private Map<String, Object>  getEmployeeList(Integer corpId, List<String> froms,List<String> tolists) {
        List<WorkEmployeeEntity> workEmployeeEntityList = workEmployeeServiceImpl.getWorkEmployeesByCorpIdsWxUserId(corpId,froms,tolists,"id,wx_user_id,name");
        Map<String,Object> map = new HashMap<>();
        //组装map并返回
        for (WorkEmployeeEntity workEmployeeEntity: workEmployeeEntityList) {
            map.put(workEmployeeEntity.getWxUserId(),workEmployeeEntity);
        }
        return map;
    }

}
